﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using DotNetUI.Controls;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

using Xc.DataAccess.Core.Services;
using Xc.DataAccess.HyperTerminalCore.Models;
using Xc.DataAccess.HyperTerminalCore.Services;
using Xc.Views.Booster.Views;
using Xc.Views.Core;

namespace Xc.Logics.HyperTerminalCore.Udp.Views
{
    /// <summary>
    /// MainView.xaml 的交互逻辑
    /// </summary>
    public partial class MainView : UserControl
    {
        private readonly IUdpServerFactory udpServerFactory;
        private readonly IApplicationBooster<Xc.Logics.HyperTerminalCore.Udp.Models.AppSetting> applicationBooster;
        private IOptionsSnapshot<Xc.Logics.HyperTerminalCore.Udp.Models.AppSetting> options
        {
            get
            {
              return   serviceProvider.CreateScope().ServiceProvider.GetService<IOptionsSnapshot<Models.AppSetting>>();
            }
        }
        private readonly IServiceProvider serviceProvider;
        public MainView(IUdpServerFactory udpServerFactory, IApplicationBooster<Xc.Logics.HyperTerminalCore.Udp.Models.AppSetting> applicationBooster, IServiceProvider serviceProvider)
        {
            InitializeComponent();
            this.udpServerFactory = udpServerFactory;
            this.applicationBooster = applicationBooster;
            this.serviceProvider = serviceProvider;

            this.ViewModel.UdpServerOption = options.Value.UdpServerOption;
            this.ViewModel.PackageInfo = options.Value.PackageInfo;

        }

        private async void DotNetButton_Click(object sender, RoutedEventArgs e)
        {
          var res= (await  udpServerFactory.SetServiceAsync(new UdpServerOption {Dispatcher=this.Dispatcher,Encoding= options.Value.UdpServerOption.Encoding, Port=this.ViewModel.UdpServerOption.Port,ServiceIndex=this.ViewModel.UdpServerOption.Port, TimeOut= options.Value.UdpServerOption.TimeOut })).FirstOrDefault();
            if (res.IsError)
            {
                MessageBox.Show(res.Message,"错误",MessageBoxButton.OK,MessageBoxImage.Error);
                return;
            }
            else
            {
                res.Infos.ClientOnlineEvent += Infos_ClientOnlineEvent;
                res.Infos.ClientOfflineEvent += Infos_ClientOfflineEvent;
                options.Value.UdpServerOption = this.ViewModel.UdpServerOption;
                applicationBooster.UpdateAppSettingFile(options.Value);
                this.ViewModel.UdpServers.Add(res.Infos);
                this.ViewModel.UdpServerOption.Port++;
            }
        }

        private void Infos_ClientOfflineEvent(UdpClientOnlineInfo obj)
        {
            Svc_OnCloing(obj);
        }

        private  void Infos_ClientOnlineEvent(UdpClientOnlineInfo service)
        {
          this.Dispatcher.Invoke(() => 
          { 
              _tab.Items.Add(new DotNetTableItem { DataContext = service, Header = service.Address, IsSelected = false, Content = new TerminalView(service, serviceProvider, options.Value.UdpServerOption.Encoding) }); 
          });

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button button)
            {
                if (button.DataContext is IUdpServerService service)
                {
                    foreach (var item in service.UdpClientOnlineInfos)
                    {
                        item.UpdateDateTime = DateTime.MinValue;
                        var d = _tab.Items.OfType<DotNetTableItem>().Where(p => p.Header?.ToString() == item.Address).FirstOrDefault();
                        if (d != null)
                        {
                            _tab.Items.Remove(d);
                        }
                    }
                    service.Close();
                    this.ViewModel.UdpServers.Remove(service);
                }
            }
        }
        /// <summary>
        /// 打开指定页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _btn_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button button)
            {
                if (button.DataContext is UdpClientOnlineInfo service)
                {
                    var item = _tab.Items.OfType<DotNetTableItem>().Where(p => p.Header?.ToString() == service.Address).FirstOrDefault();

                    if (item == null)
                    {
                        Infos_ClientOnlineEvent(service);
                    }
                    else
                    {
                        item.IsSelected = true;
                    }
                }
            }
        }
        private void Svc_OnCloing(UdpClientOnlineInfo obj)
        {
            this.Dispatcher.Invoke(() => {
                var item = _tab.Items.OfType<DotNetTableItem>().Where(p => p.Header?.ToString() == obj.Address).FirstOrDefault();

                if (item != null)
                {
                    _tab.Items.Remove(item);
                }
            });

        }
        private void Button_Click2(object sender, RoutedEventArgs e)
        {
            if (sender is Button button)
            {
                if (button.DataContext is UdpClientOnlineInfo service)
                {
                    service.UpdateDateTime = DateTime.MinValue;
                    Svc_OnCloing(service);
                }
            }
        }

        private void DotNetButton_Click_1(object sender, RoutedEventArgs e)
        {
            serviceProvider.GetDotNetWindowService<SettingView>().SetTitle("参数配置").SetWindowStartupLocation(WindowStartupLocation.CenterScreen).SetSizePercent(0.6).ShowDialog();
            this.ViewModel.UdpServerOption = options.Value.UdpServerOption;
            this.ViewModel.PackageInfo = options.Value.PackageInfo;

        }

        private void DotNetButton_Click_2(object sender, RoutedEventArgs e)
        {
            serviceProvider.GetDotNetWindowService<PackageView>().SetTitle("升级包配置").SetWindowStartupLocation(WindowStartupLocation.CenterScreen).SetSizePercent(0.6).ShowDialog();
            this.ViewModel.UdpServerOption = options.Value.UdpServerOption;
            this.ViewModel.PackageInfo = options.Value.PackageInfo;

        }
    }
}
